const { Sequelize } = require("sequelize");

// 数据库连接配置
const sequelize = new Sequelize(
  process.env.DB_NAME || 'promote_putonghua',
  process.env.DB_USER || 'root', 
  process.env.DB_PASS || 'password',
  {
    host: process.env.DB_HOST || 'localhost',
    dialect: 'mysql',
    logging: process.env.NODE_ENV === 'development' ? console.log : false,
    timezone: '+08:00',
    pool: {
      max: 10,
      min: 0,
      acquire: 30000,
      idle: 10000
    },
    define: {
      freezeTableName: true,    // 表名不复数化
      timestamps: true,         // 自动时间戳
      createdAt: 'created_at',  // 自定义时间字段名
      updatedAt: 'updated_at',
      charset: 'utf8mb4',
      collate: 'utf8mb4_unicode_ci'
    }
  }
);

// 测试数据库连接
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
  } catch (error) {
    console.error('数据库连接失败:', error);
  }
};

// 同步数据库模型
const syncDatabase = async (force = false) => {
  try {
    await sequelize.sync({ force });
    console.log('数据库模型同步成功');
  } catch (error) {
    console.error('数据库模型同步失败:', error);
  }
};

module.exports = {
  sequelize,
  testConnection,
  syncDatabase
};
